// pages/task/task.js
var app = getApp();
var canUp=true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tasksList:[],
    userinfo:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.taskList();
    this.getUser();
  },

  /*** 生命周期函数--监听页面显示 */
  onShow: function () {

  },
  //获取用户信息
  getUser() {
    wx.showLoading()
    var that = this;
    app.ajax({
      url: "User/User/getUser",
      data: {},
      success: function (res) {
        wx.hideLoading()
        if (res.data.code == 1000) {
          that.setData({
            userinfo: res.data.data
          });
        } else {
          app.showModal('获取用户信息失败');
        }
      }
    })
  },
  //获取金额列表
  taskList() {
    var that = this;
    app.ajax({
      url: 'User/Task/taskList',//
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            tasksList: res.data.data,
          })
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })
  },
  
  // 跳转积分规则
  ruleBtn: function () {
    wx.navigateTo({
      url: '../integralRule/integralRule?task=1',
    })
  },
  //解析用户信息
  bindgetuserinfofun: function (e) {
    var that = this;
    var { id, k} = e.currentTarget.dataset;
    if (e.detail.errMsg == 'getUserInfo:fail:cancel to confirm login' || e.detail.errMsg == 'getUserInfo:fail auth deny') {
      app.showToast("已取消授权", "none", 2000, function () { });
    } else {
      //that.editUserInfo(e.detail.userInfo); //更新一次用户信息
      that.getIntegral(id, k, e.detail.userInfo);
      wx.setStorageSync('avatarUrl', e.detail.userInfo.avatarUrl); //缓存头像
      wx.setStorageSync('nickName', e.detail.userInfo.nickName); //缓存名称
    }
  },
  //兑换积分
  getIntegral(id, k, userMsg){
    var that=this;
     if (!canUp){return false};
    canUp=false;
    app.ajax({
      url: "User/Task/receive",
      data: {
        id: id,
        avatar_img: userMsg.avatarUrl,
        username: userMsg.nickName,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.getUser();
          var tasksList=that.data.tasksList;
          tasksList[k].is_receive=1;
          that.setData({
            tasksList
          })
        }
        //兑换积分加一个开关;//开关生效时间2秒
        setTimeout(()=>{
          canUp=true;
        },2000);
        app.showToast(res.data.message, "none", 2000, function () { });
      }
    })
  },
  //修改用户信息
  editUserInfo(userMsg) {
    var that = this;
    app.ajax({
      url: "User/User/editUserInfo",
      data: {
        avatar_img: userMsg.avatarUrl,
        username: userMsg.nickName,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          console.log('更新新成功');
        } else {
          console.log('更新失败...', res.data.message)
          //app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })
  },
})